<template>
  <!-- 只有总页数大于1时才显示 -->
  <div class="pager-container" v-if="pageNumber > 1">
    <a @click="handleClick(1)" :class="{ disabled: current === 1 }"> 首页 </a>
    <a @click="handleClick(current - 1)" :class="{ disabled: current === 1 }"> 上一页 </a>
    <a @click="handleClick(n)" v-for="(n, i) in numbers" :key="i" :class="{ active: n === current }" class="number">
      {{ n }}
    </a>

    <a @click="handleClick(current + 1)" :class="{ disabled: current === pageNumber }"> 下一页 </a>
    <a @click="handleClick(pageNumber)" :class="{ disabled: current === pageNumber }"> 尾页 </a>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/var.scss';

.pager-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
  .number {
    width: 20px;
    text-align: center;
    border: 1px solid $primary;
    margin: 0 4px;
    padding: 2px 0;
  }
  a {
    color: $primary;
    margin: 0 6px;
    line-height: 1;
    cursor: pointer;

    &.disabled {
      color: $lightWords;
      cursor: not-allowed;
    }

    &.active {
      color: $words;
      font-weight: bold;
      cursor: text;
      border: 1px solid #000;
    }
  }
}
</style>

<script setup>
import { computed } from 'vue'
const props = defineProps({
  current: {
    type: Number,
    default: 1
  },
  total: {
    type: Number,
    default: 0
  },
  limit: {
    type: Number,
    default: 10
  },
  visibleNumber: {
    type: Number,
    default: 10
  }
})
const $emit = defineEmits(['pageChange'])
const pageNumber = computed(() => {
  return Math.ceil(props.total / props.limit)
})
const visibleMin = computed(() => {
  let min = props.current - Math.floor(props.visibleNumber / 2)
  if (min < 1) {
    min = 1
  }
  return min
})
const visibleMax = computed(() => {
  let max = visibleMin.value + props.visibleNumber - 1
  if (max > pageNumber.value) {
    max = pageNumber.value
  }
  return max
})
const numbers = computed(() => {
  let nums = []
  for (let i = visibleMin.value; i <= visibleMax.value; i++) {
    nums.push(i)
  }
  return nums
})

function handleClick(newPage) {
  if (newPage < 1) {
    newPage = 1
  }
  if (newPage > pageNumber.value) {
    newPage = pageNumber.value
  }
  if (newPage === props.current) {
    return
  }
  // 抛出一个事件
  $emit('pageChange', newPage)
}
</script>
